//
//  NetWorkTool.swift
//  SinaWeibo--swift
//
//  Created by 蒋春萌 on 15/10/8.
//  Copyright © 2015年 蒋春萌. All rights reserved.
//

import UIKit
import AFNetworking

//线上接口
private let APP_ROOT_URL = "https://api.weibo.com/"

class NetWorkTool: AFHTTPSessionManager {

    let WB_client_id = "3760913003"
    let WB_redirect_uri = "http://www.baidu.com"
    let WB_client_secret  = "5613f780ddcef42f11d63555c247f788"
    let pageUrl = "https://api.weibo.com/oauth2/authorize"
    
//    创建单例对象
    static let sharedTools:NetWorkTool = {
        
        let url = NSURL(string: APP_ROOT_URL)
        let tools = NetWorkTool(baseURL: url)
        //AFN反序列化 默认支持 @"application/json", @"text/json", @"text/javascript"
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
//    加载授权页面
    func loadOauthPage()->NSURL{
    
        let urlString = pageUrl + "?" + "client_id=" + WB_client_id + "&redirect_uri=" + WB_redirect_uri
        let url = NSURL(string: urlString)!
        
        return url
    }
    
//    获取token
    func loadAccountToken(code:String){
        
//        拼接POST请求的参数
        let urlString = "oauth2/access_token"
        let parameters = ["client_id":WB_client_id,"client_secret":WB_client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_redirect_uri]
        
//        发送POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//            如果获取成功，保存到用户账号信息中
            let account = UserAccount(dict: result as! [String:AnyObject])
            print(account)
            }) { (_, error) -> Void in
//                如果失败，打印错误信息
                print(error)
        }
    }
}
